package ru.ssau.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import ru.ssau.university.persistence.entity.Admin;
import ru.ssau.university.persistence.entity.Department;
import ru.ssau.university.persistence.entity.Faculty;
import ru.ssau.university.persistence.entity.Group;
import ru.ssau.university.persistence.entity.PlanItem;
import ru.ssau.university.persistence.entity.Progress;
import ru.ssau.university.persistence.entity.Schedule;
import ru.ssau.university.persistence.entity.Speciality;
import ru.ssau.university.persistence.entity.Student;
import ru.ssau.university.persistence.entity.Subject;
import ru.ssau.university.persistence.entity.Teacher;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();
	private static Session session = null;

	private static SessionFactory buildSessionFactory() {
		try {
			return new Configuration()
				    .addAnnotatedClass(Faculty.class)
				    .addAnnotatedClass(Teacher.class)
				    .addAnnotatedClass(Speciality.class)
				    .addAnnotatedClass(Subject.class)
				    .addAnnotatedClass(Department.class)
				    .addAnnotatedClass(Admin.class)
				    .addAnnotatedClass(PlanItem.class)
				    .addAnnotatedClass(Group.class)
				    .addAnnotatedClass(Student.class)
				    .addAnnotatedClass(Schedule.class)
				    .addAnnotatedClass(Progress.class)				    
					.configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			ex.printStackTrace();
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public static Session getSession() {
		if (session == null || !session.isOpen()) {
			session = getSessionFactory().openSession();
		} 
		return session;
	}

}
